package com.zhongjian.technologycal.mall.base;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.IntRange;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;


import com.githang.statusbar.StatusBarCompat;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.activity.LoginActivity;
import com.zhongjian.technologycal.mall.activity.personal.activity.ServiceCenterActivity;
import com.zhongjian.technologycal.mall.baserx.RxManager;
import com.zhongjian.technologycal.mall.manager.AndroidBugWorkaround;
import com.zhongjian.technologycal.mall.utils.StatusBarUtil;
import com.zhongjian.technologycal.mall.utils.TUtil;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;
import com.zhongjian.technologycal.mall.view.GetDialog;

import java.lang.reflect.Field;

import butterknife.ButterKnife;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;
import me.drakeet.materialdialog.MaterialDialog;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Activity基类，所有Activity应该继承此类
 * <p>
 * Author:wei
 * Date: 2017-10-25  14:33
 * * ************************************************************************
 * **                              _oo0oo_                               **
 * **                             o8888888o                              **
 * **                             88" . "88                              **
 * **                             (| -_- |)                              **
 * **                             0\  =  /0                              **
 * **                           ___/'---'\___                            **
 * **                        .' \\\|     |// '.                          **
 * **                       / \\\|||  :  |||// \\                        **
 * **                      / _ ||||| -:- |||||- \\                       **
 * **                      | |  \\\\  -  /// |   |                       **
 * **                      | \_|  ''\---/''  |_/ |                       **
 * **                      \  .-\__  '-'  __/-.  /                       **
 * **                    ___'. .'  /--.--\  '. .'___                     **
 * **                 ."" '<  '.___\_<|>_/___.' >'  "".                  **
 * **                | | : '-  \'.;'\ _ /';.'/ - ' : | |                 **
 * **                \  \ '_.   \_ __\ /__ _/   .-' /  /                 **
 * **            ====='-.____'.___ \_____/___.-'____.-'=====             **
 * **                              '=---='                               **
 * ************************************************************************
 * **                        佛祖保佑      镇类之宝                         **
 * ************************************************************************
 */

public abstract class BaseActivity<T extends BasePresenter, E extends BaseModel> extends AppCompatActivity implements BGASwipeBackHelper.Delegate {

    private CompositeSubscription mCompositeSubscription;

    protected BGASwipeBackHelper mSwipeBackHelper;
    public T mPresenter;
    public E mModel;
    public Context mContext;
    public RxManager mRxManager;
    public GetDialog getDialog = null;
    private LoginOutReceiver loginOutReceiver;
    private static AlertDialog.Builder dialogBuilder = null;
    private static AlertDialog alertDialog = null;

    /**
     * 获取布局ID
     *
     * @return 布局id
     */
    protected abstract int getContentViewLayoutID();


    /**
     * 界面初始化前期准备
     */
    protected void beforeInit() {

    }

    protected void initViewListener() {

    }

    /**
     * 初始化布局以及View控件View
     */
    protected abstract void initView(Bundle savedInstanceState);

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
        AndroidBugWorkaround.assistActivity(findViewById(android.R.id.content));
        mRxManager = new RxManager();
        ButterKnife.bind(this);

        mContext = this;
        mPresenter = TUtil.getT(this, 0);
        mModel = TUtil.getT(this, 1);
        if (mPresenter != null) {
            mPresenter.mContext = this;
        }
        this.initPresenter();

    }

    //简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
    public abstract void initPresenter();

    public CompositeSubscription getCompositeSubscription() {
        checkSubscription();
        return this.mCompositeSubscription;
    }

    /**
     * 检查是否为空，以免导致空指针
     */
    private void checkSubscription() {
        if (this.mCompositeSubscription == null) {
            this.mCompositeSubscription = new CompositeSubscription();
        }

    }

    /**
     * 增加一个调度器
     */
    protected void addSubscription(Subscription s) {
        checkSubscription();
        this.mCompositeSubscription.add(s);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackManager.getInstance().init(this) 来初始化滑动返回」
        // 在 super.onCreate(savedInstanceState) 之前调用该方法
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.border_color), true);
        initSwipeBackFinish();
        super.onCreate(savedInstanceState);
        getDialog = new GetDialog();
        beforeInit();
        if (getContentViewLayoutID() != 0) {
            setContentView(getContentViewLayoutID());
            initView(savedInstanceState);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (this.mCompositeSubscription != null && !this.mCompositeSubscription.isUnsubscribed()) {
            this.mCompositeSubscription.unsubscribe();
        }
    }

    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackManager.getInstance().init(this) 来初始化滑动返回」
        // 下面几项可以不配置，

        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(true);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(true);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {

    }

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    @Override
    public void onSwipeBackLayoutCancel() {
    }

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    @Override
    public void onSwipeBackLayoutExecuted() {
        mSwipeBackHelper.swipeBackward();
    }

    @Override
    public void onBackPressed() {
        // 正在滑动返回的时候取消返回按钮事件
        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //注册广播
    @Override
    protected void onResume() {
        IntentFilter fliter = new IntentFilter();
        fliter.addAction("com.broadcast.info_out_line");
        loginOutReceiver = new LoginOutReceiver();
        registerReceiver(loginOutReceiver, fliter);
        super.onResume();
    }

    //注销广播
    @Override
    protected void onPause() {
        unregisterReceiver(loginOutReceiver);
        super.onPause();
    }

    private class LoginOutReceiver extends BroadcastReceiver {

        public LoginOutReceiver() {

        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (alertDialog != null && alertDialog.isShowing()) {
                // A dialog is already open, wait for it to be dismissed, do nothing
            } else {
                if (UserUtils.getUserToken() == null || UserUtils.getUserToken().equals("")) {
                    return;
                }
                dialogBuilder = new AlertDialog.Builder(context);
                dialogBuilder.setTitle("下线提示");
                dialogBuilder.setMessage(R.string.app_outline_info);
                dialogBuilder.setCancelable(false);

                dialogBuilder.setPositiveButton("重新登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent();
                        intent.setClass(getBaseContext(), LoginActivity.class);
                        startActivity(intent);
                    }
                });
                alertDialog = dialogBuilder.create();
                alertDialog.show();
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.blue));
                try {
                    Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
                    mAlert.setAccessible(true);
                    Object mAlertController = mAlert.get(alertDialog);
                    Field mMessage = mAlertController.getClass().getDeclaredField("mMessageView");
                    mMessage.setAccessible(true);
                    TextView mMessageView = (TextView) mMessage.get(mAlertController);
                    mMessageView.setTextColor(getResources().getColor(R.color.colorTextGray));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }


            }


        }
    }


}
